package com.test.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;

import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

public class Compressor {
	private static final String INPUT_JS_FILE_PATH = "./web/test-debug.js";
	
	private static final String OUTPUT_JS_FILE_PATH = "./web/test.js";
	
	private static final String INPUT_CSS_FILE_PATH = "./web/test-debug.css";
	
	private static final String OUTPUT_CSS_FILE_PATH = "./web/test.css";
	
	private static final String CHASET_NAME = "UTF-8";

	public static void compressJs() throws Exception {
		FileInputStream in = new FileInputStream(new File(INPUT_JS_FILE_PATH));
		Reader reader = new InputStreamReader(in, CHASET_NAME);
		Writer writer = null;

		JavaScriptCompressor compressor = new JavaScriptCompressor(reader,
				new ErrorReporter() {
					public void warning(String message, String sourceName,
							int line, String lineSource, int lineOffset) {
						if (line < 0)
							System.err.println("\n[WARNING] " + message);
						else
							System.err.println("\n[WARNING] " + line + ':'
									+ lineOffset + ':' + message);
					}

					public void error(String message, String sourceName,
							int line, String lineSource, int lineOffset) {
						if (line < 0)
							System.err.println("\n[ERROR] " + message);
						else
							System.err.println("\n[ERROR] " + line + ':'
									+ lineOffset + ':' + message);
					}

					public EvaluatorException runtimeError(String message,
							String sourceName, int line, String lineSource,
							int lineOffset) {
						error(message, sourceName, line, lineSource, lineOffset);
						return new EvaluatorException(message);
					}
				});
		reader.close();
		in.close();

		FileOutputStream os = new FileOutputStream(OUTPUT_JS_FILE_PATH);
		writer = new OutputStreamWriter(os);

		compressor.compress(writer, -1, true, true, true, true); // 多少换行

		writer.close();
		os.close();
	}

	private static void compressCss() throws Exception {
		FileInputStream is = new FileInputStream(new File(INPUT_CSS_FILE_PATH));
		Reader reader = new InputStreamReader(is, CHASET_NAME);

		CssCompressor compressor = new CssCompressor(reader);

		reader.close();
		is.close();

		FileOutputStream os = new FileOutputStream(new File(
				OUTPUT_CSS_FILE_PATH));
		Writer writer = new OutputStreamWriter(os, CHASET_NAME);
		compressor.compress(writer, -1); // 多少换行

		writer.close();
		os.close();
	}

	public static void main(String[] args) {
		try {
			compressJs();
			compressCss();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
